/**
 * 
 */
package sailing.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;
import org.jdesktop.application.SingleFrameApplication;

import sailing.entity.CashVoucher;
import sailing.io.file.ExcelFiles;
import sailing.listener.DATA;
import sailing.listener.DataListener;
import sailing.listener.UI;
import sailing.managers.CashVoucherManager;
import sailing.ui.base.CenterPanel;
import sailing.ui.base.DateChooser;
import sailing.ui.base.ITabPanel;
import sailing.ui.base.TopTitlePanel;
import sailing.ui.model.CashAccountTableModel;
import sailing.utils.PD;
import sailing.utils.STask;
import sailing.utils.Utils;
import cjlite.logger.Logger;
import cjlite.utils.RandomUtils;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

/**
 * @author simon
 * 
 */
public class CashAccountPanel extends AbstractJPanel implements ITabPanel {

	private static Logger logger = Logger.thisClass();
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//
	JTabbedPane tabbedpane;
	//
	private static final Color titleBgColor = new Color(183, 219, 255);

	private JTable cashAccountTable, importTable;

	private CashAccountTableModel cashAccountTableModel, importTableModel;

	private String path;

	private JTextField textDateTimefield;
	private JTextField textCategoryfield;
	private JTextField textNumberfield;
	private JComboBox comboBORLfield;
	private JTextField textSummaryfield;
	private JTextField textOppositeAccountsfield;
	private JTextField textKindfield;
	private JTextField textBorrowBalancefield;
	private JTextField textLoanAmountfield;
	private JTextField textRemainingSumfield;

	private JPanel importTablePanel;

	private JTextField importTF;

	/**
	 * @param application
	 */
	public CashAccountPanel(SingleFrameApplication application) {
		super(application);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.AbstractJPanel#initialPanel()
	 */
	@Override
	protected void initialPanel() {
		this.setLayout(new BorderLayout());
		tabbedpane = new JTabbedPane(JTabbedPane.LEFT);
		tabbedpane.setBorder(new EmptyBorder(5, 5, 5, 5));
		tabbedpane.addTab("新建条目", this.getNewRecordPanel());
		tabbedpane.addTab("明细列表", this.getDetailPanel());
		tabbedpane.addTab("Excel数据导入", this.getImportExcelPanel());
		tabbedpane.addTab("Excel数据导出", this.getExportExcelPanel());
		this.add(tabbedpane, BorderLayout.CENTER);
	}

	private JPanel getNewRecordPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
		panel.setLayout(new BorderLayout(2, 2));
		// panel.add(this.getCustomerMgtTopPanel(), BorderLayout.NORTH);
		panel.add(new TopTitlePanel("现金日记账 - 新建条目"), BorderLayout.NORTH);

		JPanel panelC = new JPanel();
		panelC.setLayout(new FlowLayout());
		panel.add(panelC, BorderLayout.CENTER);
		JPanel newRecordP = new JPanel();
		newRecordP.setBorder(new EmptyBorder(15, 15, 15, 15));
		newRecordP.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(15, 15, 15, 15);
		c.weighty = 1.0;
		c.weightx = 1.0;
		DateChooser dateChooser1 = DateChooser.getInstance("yyyy-MM-dd");
		textDateTimefield = new JTextField("单击选择日期");
		dateChooser1.register(textDateTimefield);
		JLabel labelTime = new JLabel("时间:");
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 1;
		newRecordP.add(labelTime, c);
		c.gridx = 1;
		c.gridy = 0;
		c.gridwidth = 1;
		newRecordP.add(textDateTimefield, c);
		JLabel labelCategory = new JLabel("类别:");
		textCategoryfield = new JTextField(5);
		c.gridx = 2;
		c.gridy = 0;
		c.gridwidth = 1;
		newRecordP.add(labelCategory, c);
		c.gridx = 3;
		c.gridy = 0;
		c.gridwidth = 1;
		newRecordP.add(textCategoryfield, c);
		JLabel labelNumber = new JLabel("号数:");
		textNumberfield = new JTextField(10);
		c.gridx = 0;
		c.gridy = 1;
		c.gridwidth = 1;
		newRecordP.add(labelNumber, c);
		c.gridx = 1;
		c.gridy = 1;
		c.gridwidth = 1;
		newRecordP.add(textNumberfield, c);
		JLabel labelBORL = new JLabel("借或贷:");
		String[] vals = { "借", "贷" };
		comboBORLfield = new JComboBox(vals);
		c.gridx = 2;
		c.gridy = 1;
		c.gridwidth = 1;
		newRecordP.add(labelBORL, c);
		c.gridx = 3;
		c.gridy = 1;
		c.gridwidth = 1;
		newRecordP.add(comboBORLfield, c);
		JLabel labelSummary = new JLabel("摘要:");
		textSummaryfield = new JTextField(10);
		c.gridx = 0;
		c.gridy = 2;
		c.gridwidth = 1;
		newRecordP.add(labelSummary, c);
		c.gridx = 1;
		c.gridy = 2;
		c.gridwidth = 1;
		newRecordP.add(textSummaryfield, c);
		JLabel labelOppositeAccounts = new JLabel("对方科目:");
		textOppositeAccountsfield = new JTextField(10);
		c.gridx = 2;
		c.gridy = 2;
		c.gridwidth = 1;
		newRecordP.add(labelOppositeAccounts, c);
		c.gridx = 3;
		c.gridy = 2;
		c.gridwidth = 1;
		newRecordP.add(textOppositeAccountsfield, c);
		JLabel labelKind = new JLabel("类页:");
		textKindfield = new JTextField(10);
		c.gridx = 0;
		c.gridy = 3;
		c.gridwidth = 1;
		newRecordP.add(labelKind, c);
		c.gridx = 1;
		c.gridy = 3;
		c.gridwidth = 1;
		newRecordP.add(textKindfield, c);
		JLabel labelBorrowBalance = new JLabel("借方金额:");
		textBorrowBalancefield = new JTextField(10);
		c.gridx = 2;
		c.gridy = 3;
		c.gridwidth = 1;
		newRecordP.add(labelBorrowBalance, c);
		c.gridx = 3;
		c.gridy = 3;
		c.gridwidth = 1;
		newRecordP.add(textBorrowBalancefield, c);
		JLabel labelLoanAmount = new JLabel("贷方金额:");
		textLoanAmountfield = new JTextField(10);
		c.gridx = 0;
		c.gridy = 4;
		c.gridwidth = 1;
		newRecordP.add(labelLoanAmount, c);
		c.gridx = 1;
		c.gridy = 4;
		c.gridwidth = 1;
		newRecordP.add(textLoanAmountfield, c);
		JLabel labelRemainingSum = new JLabel("余额:");
		textRemainingSumfield = new JTextField(10);
		c.gridx = 2;
		c.gridy = 4;
		c.gridwidth = 1;
		newRecordP.add(labelRemainingSum, c);
		c.gridx = 3;
		c.gridy = 4;
		c.gridwidth = 1;
		newRecordP.add(textRemainingSumfield, c);
		JButton new_btn, cancel_btn;
		c.gridx = 1;
		c.gridy = 5;
		c.gridwidth = 1;
		new_btn = new JButton("确认");
		newRecordP.add(new_btn, c);
		c.gridx = 3;
		c.gridy = 5;
		c.gridwidth = 1;
		cancel_btn = new JButton("取消");
		newRecordP.add(cancel_btn, c);
		new_btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				performOKAction();
			}
		});
		cancel_btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				performCancelAction();
			}
		});
		panelC.add(newRecordP, BorderLayout.CENTER);

		return panel;
	}

	protected void performOKAction() {

		String dateTimeStr;
		String accountCategory;
		String accountNumber;
		String accountBORL;
		String accountSummary;
		String oppositeAccount;
		String accountKind;
		String borrowBalance;
		String loanAmount;
		String accountRemainingSum;

		accountNumber = textNumberfield.getText();
		dateTimeStr = textDateTimefield.getText();
		Date dateTime = Utils.dateParse(dateTimeStr);
		accountCategory = textCategoryfield.getText();
		accountNumber = textNumberfield.getText();
		accountBORL = (String) comboBORLfield.getSelectedItem();
		accountSummary = textSummaryfield.getText();
		oppositeAccount = textOppositeAccountsfield.getText();
		accountKind = textKindfield.getText();
		borrowBalance = textBorrowBalancefield.getText();
		loanAmount = textLoanAmountfield.getText();
		accountRemainingSum = textRemainingSumfield.getText();
		if (accountNumber.trim().length() == 0) {
			JOptionPane.showMessageDialog(this, "请输入号数。", "提示！", JOptionPane.WARNING_MESSAGE);
			return;
		}
		CashVoucherManager cm = this.getApplication().getContext().getIoc().getInstance(CashVoucherManager.class);
		CashVoucher c;

		c = new CashVoucher();
		c.setId(RandomUtils.randomString16());
		c.setAccountBORL(accountBORL);
		c.setAccountCategory(accountCategory);
		c.setAccountKind(accountKind);
		c.setAccountNumber(accountNumber);
		c.setAccountRemainingSum(accountRemainingSum);
		c.setAccountSummary(accountSummary);
		c.setBorrowBalance(borrowBalance);
		c.setDateTime(dateTime.getTime());
		c.setLoanAmount(loanAmount);
		c.setOppositeAccount(oppositeAccount);
		c.setCreateTime(System.currentTimeMillis());
		String msg = cm.save(c);
		if (msg == null || msg.length() == 0) {
			JOptionPane.showMessageDialog(this, "添加成功！");
			this.setVisible(false);
			UI.refresh();
		} else {
			JOptionPane.showMessageDialog(this, msg, "提示！", JOptionPane.WARNING_MESSAGE);
		}

	}

	protected void performCancelAction() {
		this.setVisible(false);
	}

	private JPanel getDetailPanel() {

		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
		panel.setLayout(new BorderLayout(10, 10));
		// panel.add(this.getCustomerMgtTopPanel(), BorderLayout.NORTH);
		panel.add(new TopTitlePanel("现金日记账 - 明细列表"), BorderLayout.NORTH);

		cashAccountTable = new JTable();
		cashAccountTableModel = new CashAccountTableModel(this.getApplication());
		cashAccountTable.setModel(cashAccountTableModel);
		cashAccountTable.setRowHeight(35);
		cashAccountTable.setIntercellSpacing(new Dimension(15, 5));
		cashAccountTableModel.updateModel();
		JScrollPane scrollpane = new JScrollPane(cashAccountTable);

		// scrollpane.setUI(new PlasticScrollPaneUI());
		scrollpane.setBackground(this.getBackground());
		panel.add(scrollpane, BorderLayout.CENTER);

		DATA.addDataListener(new DataListener() {

			@Override
			public void dataChanged() {
				cashAccountTableModel.updateModel();
			}
		});

		panel.add(this.getCenterPanel(), BorderLayout.CENTER);

		return panel;

	}

	private Component getCenterPanel() {
		return new CenterPanel(this.getApplication());
	}

	private JPanel getImportExcelPanel() {

		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
		panel.setLayout(new BorderLayout(2, 2));
		// panel.add(this.getCustomerMgtTopPanel(), BorderLayout.NORTH);
		panel.add(new TopTitlePanel("现金日记账 - Excel数据导入"), BorderLayout.NORTH);

		JPanel panelC = new JPanel();
		panelC.setLayout(new BorderLayout());
		panelC.setBackground(new Color(255, 255, 255));

		panelC.add(this.getImportFilePanel(), BorderLayout.NORTH);
		// importTablePanel = new FormDebugPanel(true, true);
		importTablePanel = new JPanel();
		panelC.add(this.getImportTablePanel(importTablePanel, false, null), BorderLayout.CENTER);

		panel.add(panelC, BorderLayout.CENTER);
		return panel;
	}

	private Component getImportTablePanel(JPanel panel, boolean hasImport, List<CashVoucher> cvList) {
		panel.removeAll();

		FormLayout layout = new FormLayout("3dlu,280dlu:G,5dlu,90dlu,3dlu", "2dlu,f:100dlu:g,3dlu,20dlu");
		panel.setLayout(layout);

		if (!hasImport) {
			panel.doLayout();
			return panel;
		}
		// JPanel panel = new FormDebugPanel(true, true);
		// JPanel panel = new JPanel();

		CellConstraints cc = new CellConstraints();

		this.importTableModel = new CashAccountTableModel(this.getApplication());

		this.importTable = new JTable();
		importTable.setModel(importTableModel);
		this.importTableModel.updateModel(cvList);
		// panel.add(new JLabel("no data"));

		JScrollPane scrollPane = new JScrollPane(importTable);
		scrollPane.setBackground(this.getBackground());
		panel.add(scrollPane, cc.xywh(2, 2, 3, 1));

		JButton importDatabtn;
		importDatabtn = new JButton("导入所有数据到数据库中");
		importDatabtn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
		importDatabtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				performImportDataToDB();
			}
		});
		panel.add(importDatabtn, cc.xy(4, 4));
		panel.doLayout();
		return panel;
	}

	protected void performImportDataToDB() {
		PD.execute(this, new STask() {

			@Override
			public void run() {
				this.setMsg("开始保存.....");
				CashVoucherManager cm = getApplication().getContext().getIoc().getInstance(CashVoucherManager.class);

				if (cm.saveList(importTableModel.getDataList())) {

				}

				this.setMsg("保存到数据库完成.....");
				this.afterMsg("保存到数据库完成.....");
			}

		});

	}

	private Component getImportFilePanel() {

		// JPanel importFilePanel = new FormDebugPanel(true, true);
		JPanel importFilePanel = new JPanel();
		importFilePanel.setBorder(new EmptyBorder(10, 15, 6, 15));

		FormLayout layout = new FormLayout("10dlu,f:250dlu:g,5dlu,72dlu,10dlu", "1dlu,f:18dlu,1dlu");
		importFilePanel.setLayout(layout);

		CellConstraints cc = new CellConstraints();

		importTF = new JTextField(30);
		importTF.setEditable(false);
		importFilePanel.add(importTF, cc.xy(2, 2));

		JButton new_btn;
		new_btn = new JButton("选择要导入的Excel");
		new_btn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
		importFilePanel.add(new_btn, cc.xy(4, 2));
		new_btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String filePath = ExcelFiles.getImportFile(CashAccountPanel.this);
				parseExcelFile(filePath);
			}
		});

		return importFilePanel;
	}

	protected void parseExcelFile(String path) {
		if (path != null) {
			this.importTF.setText(path);
			List<CashVoucher> cvList = ExcelFiles.loadData("导入 现金日记账", this, path, CashVoucher.class);
			this.getImportTablePanel(importTablePanel, true, cvList);

		} else {
			logger.trace("file path='{0}'", path);
		}
	}

	private JPanel getExportExcelPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 0));
		panel.setLayout(new BorderLayout(10, 10));
		// panel.add(this.getCustomerMgtTopPanel(), BorderLayout.NORTH);
		panel.add(new TopTitlePanel("现金日记账 - Excel数据导出"), BorderLayout.NORTH);

		cashAccountTable = new JTable();
		JScrollPane scrollpane = new JScrollPane(cashAccountTable);
		// scrollpane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		// Set the frame characteristics
		setSize(300, 200);
		// Create columns names
		String columnNames[] = { "Column 1", "Column 2", "Column 3" };

		// Create some data
		String dataValues[][] = { { "12", "234", "67" }, { "-123", "43", "853" }, { "93", "89.2", "109" },
				{ "279", "9033", "3092" } };

		// Create a new table instance
		cashAccountTable = new JTable(dataValues, columnNames);

		// Add the table to a scrolling pane
		scrollpane = new JScrollPane(cashAccountTable);

		panel.add(scrollpane, BorderLayout.CENTER);

		return panel;
	}

	private JPanel getCustomerMgtTopPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createEtchedBorder());
		panel.setBackground(titleBgColor);
		panel.setOpaque(true);
		panel.add(new JLabel("现金日记账"));
		return panel;
	}

	protected void refreshDataModel() {
		if (cashAccountTableModel != null) {
			cashAccountTableModel.fireTableDataChanged();
		}
	}

	@Override
	public String getTabName() {
		return "现金日记账";
	}

	@Override
	public JPanel getContentPanel() {
		return this;
	}

	@Override
	public Icon getTabIcon() {
		return null;
	}

	@Override
	public String getTabTip() {
		return null;
	}

}
